package com.meisiabc.support.wechat;

import com.riversoft.weixin.pay.base.PaySetting;
import com.riversoft.weixin.pay.payment.Payments;
import com.riversoft.weixin.pay.payment.Signatures;
import com.riversoft.weixin.pay.payment.bean.PaymentNotification;
import com.riversoft.weixin.pay.payment.bean.Signature;
import com.riversoft.weixin.pay.payment.bean.UnifiedOrderRequest;
import com.riversoft.weixin.pay.payment.bean.UnifiedOrderResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class WechatPay {
    private static final String NOTIFY_URL = "https://www.meisiabc.cn/app/order/payCallback";
    private static final String BILL_CREATED_IP = "127.0.0.1";
    private PaySetting paySetting;

    public WechatPay() {
        this.paySetting = new PaySetting();
        this.paySetting.setAppId("wxd10308eaab66e9b4");
        this.paySetting.setMchId("1515575541");
        this.paySetting.setKey("9HNnL3xQRUGlVQio16q9HjkqAZ5rA0nX");
        this.paySetting.setCertPath("/opt/meisi/meisi-app/cert/apiclient_cert.p12");
        this.paySetting.setCertPassword("1515575541");
    }

    public String prepay(String openid, String body, String tradeNumber, int totalFee) {
        return prepay(openid, body, tradeNumber, totalFee, BILL_CREATED_IP, NOTIFY_URL);
    }

    public String prepay(String openid, String body, String tradeNumber, int totalFee, String billCreatedIp, String notifyUrl) {
        UnifiedOrderRequest request = new UnifiedOrderRequest();
        request.setOpenId(openid);
        request.setBody(body);
        request.setTradeNumber(tradeNumber);
        request.setTotalFee(totalFee);
        request.setBillCreatedIp(billCreatedIp);
        request.setNotifyUrl(notifyUrl);
        request.setTradeType("JSAPI");

        UnifiedOrderResponse unifiedOrderResponse = Payments.with(this.paySetting).unifiedOrder(request);

        log.info("UnifiedOrderResponse.{}", unifiedOrderResponse);

        if (unifiedOrderResponse.success()) {
            return unifiedOrderResponse.getPrepayId();
        }

        return null;
    }

    public Signature createJsSignature(String prepayId) {
        try {
            return Signatures.with(this.paySetting).createJsSignature(prepayId);
        } catch (Exception e) {
            log.error("createJsSignature fail.{prepayId={}}", prepayId, e);
        }

        return null;
    }

    public boolean checkSignature(PaymentNotification notification) {
        return Payments.with(this.paySetting).checkSignature(notification);
    }
}
